package org.usmile.algorithms.learn.graph.bfs;

import org.usmile.algorithms.learn.graph.AdjList;
import org.usmile.algorithms.learn.graph.Graph;

import java.util.*;

public class SingleSourcePath {
    public int[] sourcePath(Graph graph) {
        if (graph == null) {
            return new int[0];
        }

        Queue<Integer> queue = new LinkedList<>();
        int[] prevs = new int[graph.getV()];
        Arrays.fill(prevs, -1);
        for (int v = 0; v < graph.getV(); v++) {
            if (prevs[v] == -1) {
                queue.offer(v);
                prevs[v] = v;
                while (!queue.isEmpty()) {
                    int curr = queue.poll();
                    for (int w : graph.adj(curr)) {
                        if (prevs[w] == -1) {
                            queue.add(w);
                            prevs[w] = curr;
                        }
                    }
                }
            }
        }

        return prevs;
    }

    public static void main(String[] args) {
        Graph graph = new AdjList(5);
        graph.addEdge(0, 1);
        graph.addEdge(1, 2);
        graph.addEdge(1, 4);
        graph.addEdge(3, 2);

        System.out.println(Arrays.toString(new SingleSourcePath().sourcePath(graph)));
    }
}
